package shooter.network;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * The basic message. All other message types inherit from it.
 * 
 * @author Michail Tausch
 */
public abstract class Message implements Serializable{
	
	/**
	 * The constructor.
	 */
	public Message(){		
	}
	
	/**
	 * Returns a message in form of a byte array.
	 * @return
	 * @throws IOException
	 */
	public byte[] toByteArray() throws IOException{		
		ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(this);
		return baos.toByteArray();
	}
	
	/**
	 * Calls readMessage(array). Returns the array as Message.
	 * @param array
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public Message fromByteArry(byte[] array) throws IOException, ClassNotFoundException{
		return readMessage(array);
	}
	
	/**
	 * Returns the array as Message.
	 * @param array
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static Message readMessage(byte[] array) throws IOException, ClassNotFoundException{
		ByteArrayInputStream bais = new ByteArrayInputStream(array);
		ObjectInputStream ois = new ObjectInputStream(bais);
		return (Message) ois.readObject();
	}
}

